#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include <QObject>
#include <QTcpSocket>
#include <QList>
#include <QMutex>
#include <QWaitCondition>
#include <QElapsedTimer>

class DatabaseManager : public QObject
{
    Q_OBJECT
public:
    explicit DatabaseManager(QObject *parent = nullptr);
    ~DatabaseManager();

    static DatabaseManager* instance();
    QString sendRequest(const QString &query);
    bool isConnected();

    // 禁止拷贝和赋值
    DatabaseManager(const DatabaseManager&) = delete;
    DatabaseManager& operator=(const DatabaseManager&) = delete;

private:
    // 使用静态递归锁替代成员变量
    static QMutex& globalMutex() {
        static QMutex mutex(QMutex::Recursive);  // 关键修改：静态递归锁
        return mutex;
    }

    struct Connection {
        QTcpSocket* socket;
        bool inUse;
        Connection(QTcpSocket* s = nullptr, bool u = false) : socket(s), inUse(u) {}
    };

    QList<Connection> m_connections;
    QWaitCondition m_connAvailable;
    const int MAX_CONNECTIONS = 15;

    void cleanupConnections();
    bool connectToServer(QTcpSocket* socket);
    void initializeConnections();
};

#endif // DATABASEMANAGER_H
